package com.cy.springcloud.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 权限过滤
 * @ClassName: AuthFilter
 * @Author: chenyu
 * @Date: 2025/1/7 15:49
 */
@Component
public class AuthFilter extends ZuulFilter {

    @Override
    public String filterType() {
        //pre表示在路由之前执行过滤器，其他值还有post, error, route, static, 也可以自定义
        return "pre";
    }

    @Override
    public int filterOrder() {
        //过滤器的执行顺序
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //过滤器是否执行，true表示执行，false表示不执行
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //过滤器的具体执行逻辑
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");
        if (token == null) {
            ctx.set("next", false);
            //不对该请求进行路由
            //zuul的SimpleHostRoutingFilter主要用来转发不走eureka的proxy
            ctx.setSendZuulResponse(false);
            //zuul的SendForwardFilter处理路由规则中forward的本地跳转
            ctx.set("sendForwardFilter.ran", true);
            //响应状态码
            ctx.setResponseStatusCode(401);
            ctx.addZuulResponseHeader("content-type", "text/html;charset=utf-8");
            ctx.setResponseBody("非法访问");
        }
        //run方法的返回值目前没有意义，可以返回任意值
        return null;
    }
}
